package com.lsb.blog.service.impl;

import com.alibaba.fastjson.JSON;
import com.lsb.blog.pojo.SysUser;
import com.lsb.blog.response.Result;
import com.lsb.blog.response.ResultCode;
import com.lsb.blog.service.LoginService;
import com.lsb.blog.service.SysUserService;
import com.lsb.blog.utils.JWTUtils;
import com.lsb.blog.vo.params.LoginParam;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ：liusibo
 * @description：TODO
 * @date ：2021/8/3 17:33
 */
@Service
public class LoginServiceImpl implements LoginService {

    private static final String salt = "mszlu!@#";

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public Result login(LoginParam loginParam) {
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)){
            return Result.error(ResultCode.PARAMS_ERROR);
        }
        String pwd = DigestUtils.md5Hex(password + salt);
        SysUser sysUser = sysUserService.findUser(account,pwd);
        if (sysUser == null){
            return Result.error(ResultCode.ACCOUNT_PWD_NOT_EXIST);
        }
        //登录成功，使用JWT生成token，返回token和 存入redis中
        String token = JWTUtils.createToken(sysUser.getId());
        redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
        return Result.ok().data(token);
    }

    @Override
    public Result logout(String token) {
        redisTemplate.delete("TOKEN_"+token);
        return Result.ok();
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result register(LoginParam loginParam) throws Exception{
        //判断参数
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        String nickname = loginParam.getNickname();
        if (StringUtils.isBlank(account)
                || StringUtils.isBlank(password)
                || StringUtils.isBlank(nickname)
        ){
            return Result.error(ResultCode.PARAMS_ERROR);
        }
        //插入用户数据
        SysUser sysUser = new SysUser();
        sysUser.setNickname(nickname);
        sysUser.setAccount(account);
        sysUser.setPassword(DigestUtils.md5Hex(password+salt));
        sysUser.setCreateDate(System.currentTimeMillis());
        sysUser.setLastLogin(System.currentTimeMillis());
        sysUser.setAvatar("/static/img/logo.b3a48c0.png");
        sysUser.setAdmin(true); //1 为true
        sysUser.setDeleted(false); // 0 为false
        sysUser.setSalt("");
        sysUser.setStatus("");
        sysUser.setEmail("");
        boolean save = this.sysUserService.save(sysUser);
        //查询该account用户数量,若大于1,则回滚事务
        if(save){
            int num = sysUserService.findAccountNum(account);
            if(num>1){
                throw new Exception("账号已经存在,无法注册");
            }
            //token
            String token = JWTUtils.createToken(sysUser.getId());

            redisTemplate.opsForValue().set("TOKEN_"+token, JSON.toJSONString(sysUser),1, TimeUnit.DAYS);
            return Result.ok().data(token);
        }

        return Result.error(ResultCode.ACCOUNT_EXIST);
    }


}
